import { createRouter, createWebHistory } from 'vue-router'
import RegisterCard from './components/RegisterCard.vue'
import LoginCard from './components/LoginCard.vue'
import LogoutCard from './components/LogoutCard.vue'
import HomePage from './components/HomePage.vue'
import BookingPage from './components/BookingPage.vue'
import BookingManagement from './components/BookingManagement.vue'
import RoomStatusPage from './components/RoomStatusPage.vue'
import TestApi from './components/TestApi.vue'
import AdminPage from './components/AdminPage.vue'
import RechargePage from './components/RechargePage.vue'
import api from './services/api.js'

// 创建路由配置
const routes = [
  { path: '/', component: HomePage },
  { path: '/register', component: RegisterCard },
  {
    path: '/login',
    name: 'Login',
    component: () => import('./components/LoginCard.vue')
  },
  { path: '/logout', component: LogoutCard },
  { path: '/booking', component: BookingPage },
  { path: '/management', component: BookingManagement },
  { path: '/status', component: RoomStatusPage },
  { path: '/test', component: TestApi },
  { path: '/recharge', component: RechargePage },
  { path: '/admin', component: () => import('./components/AdminDashboard.vue'), meta: { requiresAdmin: true } },
  {
    path: '/session-expired',
    name: 'SessionExpired',
    component: () => import('./components/SessionExpired.vue')
  },
  {
    path: '/admin/login',
    component: () => import('./components/AdminLogin.vue')
  },
]

// 创建路由器实例
const router = createRouter({
  history: createWebHistory(),
  routes, // 使用 `routes` 作为缩写形式
})

// 全局导航守卫：需要登录的页面自动校验
const needLogin = ['/booking', '/management', '/recharge']
router.beforeEach(async (to, from, next) => {
  if (needLogin.includes(to.path)) {
    try {
      const res = await api.checkLogin()
      if (res.data.loggedIn) {
        next()
      } else {
        // 显示登录提示弹窗
        if (typeof window !== 'undefined' && window.$root) {
          window.$root.showLoginMessage()
        }
        next('/login')
      }
    } catch (e) {
      // 显示登录提示弹窗
      if (typeof window !== 'undefined' && window.$root) {
        window.$root.showLoginMessage()
      }
      next('/login')
    }
  } else {
    next()
  }
})

export default router
